/** @format */

import ArticleItem from '@/components/ArticleItem'
import styles from './ArticleList.module.scss'
import { InfiniteScroll } from 'antd-mobile'
import { useRef, useState } from 'react'
import type { ArtItem } from '@/types/http'
import { getArtListApi } from '@/api/home'

type Props = {
  channelId: number
}
const ArticleList = ({ channelId }: Props) => {
  const [artList, setArtList] = useState<ArtItem[]>([])
  const [hasMore, setHasMore] = useState(true)
  const timestamp = useRef(String(Date.now()))
  const loadMore = async () => {
    const {
      data: {
        data: { pre_timestamp, results: artList }
      }
    } = await getArtListApi({
      channel_id: channelId,
      timestamp: timestamp.current
    })
    if (pre_timestamp === null) {
      setHasMore(false)
      return
    }
    timestamp.current = pre_timestamp
    setArtList((prev) => [...prev, ...artList])
  }
  return (
    <div className={styles.root}>
      {/* 文章列表中的每一项 */}
      <div className='article-item'>
        {artList.map((item) => (
          <ArticleItem
            {...item}
            key={item.art_id}
          />
        ))}
      </div>
      <InfiniteScroll
        loadMore={loadMore}
        hasMore={hasMore}
      />
    </div>
  )
}

export default ArticleList
